#include"circlequeue.h"

MyCircularQueue* myCircularQueueCreate(int k) {
	MyCircularQueue* ps	= (MyCircularQueue*)malloc(sizeof(MyCircularQueue));
	if (ps == NULL) {
		perror("malloc fail");
		return NULL;
	}
	int* ptr = malloc(sizeof(int) * k + 1);
	if (ptr == NULL) {
		perror("malloc fail");
		return NULL;
	}
	ps->a = ptr;
	ps->front = ps->rear = 0;
	ps->k = k;
	return ps;
}

bool myCircularQueueEnQueue(MyCircularQueue* obj, int value) {
	if (!myCircularQueueIsFull(obj)) {
		obj->a[obj->rear++] = value;
		obj->rear %= (obj->k + 1);
		return true;
	}
	return false;
}

bool myCircularQueueDeQueue(MyCircularQueue* obj) {
	if (!myCircularQueueIsEmpty(obj)) {
		obj->a[obj->front++] = 0;
		obj->front %= (obj->k + 1);
		return true;
	}
	return false;
}

int myCircularQueueFront(MyCircularQueue* obj) {
	if (myCircularQueueIsEmpty(obj)) {
		return -1;
	}
	return obj->a[obj->front];
}

int myCircularQueueRear(MyCircularQueue* obj) {
	if (myCircularQueueIsEmpty(obj)) {
		return -1;
	}
	return obj->a[(obj->rear + obj->k) % obj->k];
}

bool myCircularQueueIsEmpty(MyCircularQueue* obj) {
	return obj->front == obj->rear;
}

bool myCircularQueueIsFull(MyCircularQueue* obj) {
	return ((obj->rear + 1) % (obj->k + 1)) == obj->front;
}

void myCircularQueueFree(MyCircularQueue* obj) {
	free(obj->a);
	obj->a = NULL;
	free(obj);
	obj = NULL;
}